package com.leetroll.media.job;

import com.leetroll.api.service.ItemService;
import com.leetroll.api.service.MetricService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.entity.Metric;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.common.utils.AliyunOSSUtil;
import com.leetroll.common.utils.BaiduTranslateUtil;
import com.leetroll.media.service.UpDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * poliigon网站的资源入库 （此服务后面放到别的模块）
 */
@Service
@Slf4j
public class Job_Poliigon {

    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    //路径有变  存在存储服务器
    private static final String FILE_PATH = "F:\\test\\poliigon";
    private final MetricService metricService;
    private final ItemService itemService;
    private final UpDownloadService upDownloadService;

    @Autowired
    public Job_Poliigon(MetricService metricService, ItemService itemService, UpDownloadService upDownloadService) {
        this.metricService = metricService;
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
    }

    /**
     * 根据文件夹目录生成metric
     */
    public void generateMetrics() throws IOException {
        File folder = new File("F:\\_dev\\leetroll\\配置资源\\分类metric\\贴图");

        if (!folder.exists() || !folder.isDirectory()) return;
        File[] files = folder.listFiles();
        List<Metric> metrics = new ArrayList<>();
        if (files == null) return;
        for (File file : files) {
            String name = file.getName().split("\\.")[0];
            String zhName = BaiduTranslateUtil.translate(name);
            Metric metric = new Metric();
            metric.setParentId(1L);
            metric.setName(zhName);
            metric.setAlias(name);
            metric.setCreateTime(new Date());
            metric.setUpdateTime(new Date());

            String path = "cat/1/metrics/" + file.getName();
            AliyunOSSUtil.upload(path, Files.newInputStream(file.toPath()));
            String url = AliyunOSSUtil.GetUrl(path, 10);//10年有效期

            metric.setPreview(url);
            metrics.add(metric);

        }
        metricService.saveBatch(metrics);
        log.info("metric 插入任务完成");
    }

    public static void main(String[] args) {
        String url = AliyunOSSUtil.GetUrl("cat/1/metrics/hdri.jpg", 10);//10年有效期
        System.out.println(url);
    }

    /**
     * 上传所有贴图资源
     * # 1. 按文件名翻译, 入库
     * # 2. 按文件上传规范上传到阿里云
     */
    public void uploadTextures() throws InterruptedException {
        File folder = new File(FILE_PATH);
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] files = folder.listFiles();
        if (files == null) return;

        for (File file : files) {
            File[] textures = file.listFiles();
            if (textures == null) continue;
            for (File mainFile : textures) {
                executor.submit(() -> {
                            try {
                                uploadFile(file.getName(), mainFile);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                );
            }
        }
        Thread.sleep(1000L * 60 * 60 * 24 * 365);
        log.info("item 插入任务完成");
    }

    private void uploadFile(String tag, File mainFile) throws IOException {
        if (isZip(mainFile.getName())) return;
        log.info("准备插入 item : {}", mainFile.getName());
        String fileName = mainFile.getName();
//                String zhFileName = BaiduTranslateUtil.translate(fileName.split("\\.")[0]);
        //插入item表
        Item item = new Item();
        item.setName(fileName.split("\\.")[0]);
        item.setAlias(fileName.split("\\.")[0]);
        item.setType(EItemType.TEXTURE.getType());
        item.setAuthor("无名氏");
        item.setPrice(5.0);
        item.setCatId(1L);
        item.setStatus("show");
        item.setTag(tag);
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);

        //插入file表
        String fName = fileName.split("\\.")[0];
        String attachmentFileName = fName.replace(" ", "_") + ".rar";
        if (!new File(mainFile.getParent() + "\\" + attachmentFileName).exists()) {
            attachmentFileName = fName.replace(" ", "_") + ".zip";
        }
        String mainPath = "item/" + item.getId() + "/main/";
        String attachmentPath = "item/" + item.getId() + "/attachment/";

        File attachmentFile = new File(mainFile.getParent() + "\\" + attachmentFileName);

        AliyunOSSUtil.upload(mainPath + fileName, Files.newInputStream(mainFile.toPath()));
        AliyunOSSUtil.upload(attachmentPath + attachmentFileName, Files.newInputStream(attachmentFile.toPath()));

        upDownloadService.upload2AliByType(item.getId(), mainFile, EFileType.MAIN);
        upDownloadService.upload2AliByType(item.getId(), attachmentFile, EFileType.ATTACHMENT);

        log.info("--------------- item 插入成功 {} : {}", item.getId(), fileName);
    }

    public boolean isZip(String fileName) {
        return fileName.endsWith("zip") || fileName.endsWith("rar");
    }
}
